// 时间格式化
export function formatDate(time, fmt = 'yyyy-MM-dd') {
  let date
  if (time) {
    if (typeof time === 'object') {
      date = time
    } else {
      if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
        time = parseInt(time)
      }
      if ((typeof time === 'number') && (time.toString().length === 10)) {
        time = time * 1000
      }
      date = new Date(time)
    }
  } else {
    date = new Date()
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'a': date.getDay()
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      if (k === 'a') {
        const str = ['日', '一', '二', '三', '四', '五', '六'][o[k]]
        fmt = fmt.replace(RegExp.$1, str)
        continue
      }
      const str = o[k] + ''
      // fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
      fmt = fmt.replace(RegExp.$1, str.padStart(2, '0'))
    }
  }
  return fmt
}
/**
 *  快速获取日期
 *  num: 1 今日 2 昨日 3 本周 4 上周 5 本月
 *  bool: true 有时分秒 false | null 不要时分秒
 */
export function getDateStr(num, bool) {
  var now = new Date() // 当前日期
  var nowDayOfWeek = now.getDay() // 今天本周的第几天
  var nowDay = now.getDate() // 当前日
  var nowMonth = now.getMonth() // 当前月
  var nowYear = now.getYear() // 当前年
  nowYear += (nowYear < 2000) ? 1900 : 0 //
  var monthStartDate = new Date(nowYear, nowMonth, 1)
  var monthEndDate = new Date(nowYear, nowMonth + 1, 1)
  var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24)

  var fmt = 'yyyy-MM-dd'
  var startTime = ''
  var endTime = ''

  if (num == 1) { // 今日
    startTime = formatDate(now, fmt)
    endTime = startTime
  }
  if (num == 2) { // 昨日
    now.setDate(nowDay - 1)
    startTime = formatDate(now, fmt)
    endTime = startTime
  }
  if (num == 3) { // 本周
    startTime = formatDate(new Date(nowYear, nowMonth, nowDay - nowDayOfWeek), fmt)
    endTime = formatDate(new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek)), fmt)
  }
  if (num == 4) { // 上周
    startTime = formatDate(new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 7), fmt)
    endTime = formatDate(new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 1), fmt)
  }
  if (num == 5) { // 本月
    startTime = formatDate(new Date(nowYear, nowMonth, 1), fmt)
    endTime = formatDate(new Date(nowYear, nowMonth, days), fmt)
  }
  if (bool) {
    startTime += ' 00:00:00'
    endTime += ' 23:59:59'
  }
  return [startTime, endTime]
}

/**
 * 获取当前 0:0:0:0 时间
 */
export function getDateNow() {
  const date = new Date()
  date.setHours(0, 0, 0, 0)
  return date
}
